package com.example.myfirstapplication

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.myfirstapplication.utils.BaseActivity
import kotlinx.android.synthetic.main.activity_audio.*

class AudioActivity : BaseActivity() {

    private val mediaPlay = MediaPlayer()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio)
        initMedia()
        btnAudioPlay.setOnClickListener {
            if (!mediaPlay.isPlaying) {
                mediaPlay.start()
            }
        }
        btnAudioPause.setOnClickListener {
            if (mediaPlay.isPlaying) {
                mediaPlay.pause()
        }
        }
        btnAudioStop.setOnClickListener {
            if (mediaPlay.isPlaying) {
                mediaPlay.reset()
                initMedia()
            }
        }
    }

    private fun initMedia() {
        val assetManager = assets
        val fd = assetManager.openFd("music.mp3")
        mediaPlay.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
        mediaPlay.prepare()
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlay.stop()
        mediaPlay.release()
    }
}